<template>
  <div :style="defaultStyle" class="condition-form">
    <el-form
      :class="[!module ? 'margin_10' : '']"
      id="queryForm"
      ref="conditionFormRef"
      :model="searchFormData"
      :rules="searchRules"
      :label-position="labelPosition"
      status-icon
    >
      <div class="form-content">
        <div class="form-left">
          <el-row
            v-if="searchColumnList.length"
            :gutter="30"
            style="width: 100%"
          >
            <template
              v-for="item in searchColumnList || []"
              :key="`form_${item.prop}`"
            >
              <el-col
                :xs="item.span || 6"
                :sm="item.span || 6"
                :md="item.span || 6"
                :lg="item.span || 6"
                :xl="item.span || 6"
                v-if="!item.hide"
              >
                <!-- label-width写死90px 文字固定长度6个字符 -->
                <el-form-item
                  :class="`my-form-item el-item-col ${
                    item?.labelKeepInline ? 'label-keep-inline' : ''
                  }`"
                  :label="$t(item?.label || '')"
                  :label-width="`${item?.labelWidth ?? 'auto'}`"
                  label-position="right"
                  :prop="item.prop"
                >
                  <div
                    v-if="item.type === 'label_province_city_area'"
                    style="width: 100%; display: flex"
                  >
                    <div style="flex: 1">
                      <el-select-v2
                        style="width: 100%"
                        v-model="searchFormData[item.propSelectCode]"
                        filterable
                        :props="item.propsSelect"
                        :options="item.propSelectOptions || []"
                        :placeholder="
                          $t(item.propSelectPlaceholder || '请选择')
                        "
                        :clearable="item.clearable || true"
                        :multiple="item.multiple"
                        @clear="onPropSelectClose(item)"
                        @change="onPropSelectChange($event, item)"
                      />
                    </div>
                    <div style="flex: 2">
                      <el-cascader
                        style="width: 100%"
                        v-model="searchFormData[item.prop]"
                        :props="item.props"
                        :placeholder="$t(item.placeholder || '请选择')"
                        :options="item.options"
                        filterable
                        :clearable="item.clearable || true"
                        @clear="onCascaderClose"
                        @change="onCascaderChange($event, item)"
                      />
                    </div>
                  </div>
                  <!-- 高级日期查询控件 -->
                  <!-- <base-date-time-picker
                    v-if="item.type === 'advance_date_picker'"
                    @keyup.ctrl.enter="handleSearch"
                    v-model="searchFormData[item.prop]"
                    :type="item.dateType"
                    :shortcuts="item.shortcuts"
                    @change-range-date="item.change"
                    :style="'width: 100%;' + item?.style"
                  /> -->
                  <!-- {{ item.prop }} -->
                  <el-input
                    v-if="item.type === 'label_input'"
                    v-model="searchFormData[item.prop]"
                    @keyup.ctrl.enter="handleSearch"
                    :disabled="item.disabled"
                    :placeholder="item.placeholder || $t('请输入')"
                    clearable
                  />
                  <el-autocomplete
                    v-if="item.type === 'label_input_autocomplete'"
                    v-model="searchFormData[item.prop]"
                    :fetch-suggestions="
                      (val, cb) => {
                        querySearchAsync(val, cb, item);
                      }
                    "
                    clearable
                    :placeholder="$t(item.placeholder || '请输入')"
                    @select="handleAutocompleteSelect($event, item)"
                    @clear="handleAutocompleteClear(item)"
                  />
                  <!-- 多单查询 -->
                  <MultipleAreaInput
                    v-if="item.type === 'label_multiple_area_input'"
                    v-model="searchFormData[item.prop]"
                    :disabled="item.disabled"
                    :placeholder="item.placeholder || $t('请输入')"
                    :valueSeparator="item.valueSeparator"
                    :showSeparator="item.showSeparator"
                    clearable
                  />
                  <el-input
                    v-if="item.type === 'label_area_input'"
                    v-model="searchFormData[item.prop]"
                    :type="item.inputType"
                    :disabled="item.disabled"
                    @keyup.ctrl.enter="handleSearch"
                    :rows="item.rows || 4"
                    :placeholder="item.placeholder || $t('请输入')"
                    clearable
                  />
                  <el-select
                    :style="{
                      width: item?.otherWidth ?? '68px',
                      marginRight: '5px',
                    }"
                    v-if="item.otherOptions"
                    v-model="searchFormData[item.otherProp]"
                  >
                    <el-option
                      v-for="(opt, oindex) in item.otherOptions"
                      :key="`${oindex} ${item.otherProp}`"
                      :label="opt.label"
                      :value="opt.value"
                    />
                  </el-select>
                  <el-input-number
                    v-if="item.type === 'label_input_number'"
                    style="width: 100%"
                    v-model="searchFormData[item.prop]"
                    :min="item.min || 0"
                    :max="item.max"
                    :disabled="item.disabled"
                    :controls-position="item.controlsPosition || 'right'"
                    :controls="!!item.controls"
                    :placeholder="item.placeholder || $t('请输入')"
                    clearable
                  />
                  <RemoteSelect
                    v-if="item.type === 'remote_select'"
                    :params="item?.params"
                    :names="searchFormData[item.prop]"
                    :multiple="item?.multiple"
                    :api-module="item?.apiModule"
                    :disabled="item?.disabled"
                    @handle-remote-change="
                      (val, data) => {
                        searchFormData[item.prop] = val;
                      }
                    "
                    @handleClear="searchFormData[item.prop] = null"
                  />
                  <el-select
                    v-if="item?.type === 'label_select'"
                    v-model="searchFormData[item?.prop]"
                    :disabled="item?.disabled"
                    :placeholder="item?.placeholder || $t('请选择')"
                    :multiple="item?.multiple"
                    :props="item?.props"
                    :collapse-tags="item?.multiple"
                    :collapse-tags-tooltip="item?.multiple"
                    @change="
                      item.handleChange
                        ? item.handleChange(searchFormData[item?.prop])
                        : ''
                    "
                    @keyup.ctrl.enter="handleSearch"
                    :clearable="item.clearable !== false"
                  >
                    <el-option
                      v-for="it in item.options || []"
                      :key="it?.value || it?.name"
                      :label="it[item['labelName']] || it?.label || it?.subName"
                      :value="
                        it[item['labelVal']] ||
                        it?.value ||
                        it?.subCode ||
                        it?.name
                      "
                    />
                  </el-select>
                  <el-radio-group
                    v-if="item.type === 'label_radio_group'"
                    v-model="searchFormData[item.prop]"
                  >
                    <el-radio
                      v-for="it in item.options || []"
                      :disabled="it.disabled"
                      :key="it.value"
                      :value="it.value"
                      >{{ $t(it.label) }}</el-radio
                    >
                  </el-radio-group>
                  <el-checkbox-group
                    v-if="item.type === 'label_checkbox_group'"
                    v-model="searchFormData[item.prop]"
                  >
                    <el-checkbox
                      v-for="it in item.options || []"
                      :disabled="it.disabled"
                      :key="it.value"
                      :label="it.value"
                      >{{ $t(it.label) }}</el-checkbox
                    >
                  </el-checkbox-group>
                  <el-switch
                    v-if="item.type === 'label_input_switch'"
                    v-model="searchFormData[item.prop]"
                    :active-text="item.activeText"
                    :active-value="item.activeValue"
                    :inactive-text="item.inactiveText"
                    :inactive-value="item.inactiveValue"
                  />

                  <el-time-picker
                    v-if="item.type === 'label_time_picker'"
                    v-model="searchFormData[item.prop]"
                    is-range
                    range-separator="-"
                    :value-format="item.format"
                    :start-placeholder="$t('开始时间')"
                    :end-placeholder="$t('结束时间')"
                    :placeholder="$t('选择时间范围')"
                    :clearable="false"
                    @keydown="handleKeyDown"
                  />
                  <el-date-picker
                    v-if="item.type == 'label_date_picker'"
                    v-model="searchFormData[item.prop]"
                    :type="item.dateType || 'date'"
                    clearable
                    :picker-options="item.pickerOptions"
                    :placeholder="
                      item.placeholder
                        ? $t(`${item.placeholder}`)
                        : $t('请选择')
                    "
                    :start-placeholder="$t(item.startPlaceholder || '开始日期')"
                    :end-placeholder="$t(item.endPlaceholder || '结束日期')"
                    :format="
                      item.format ||
                      (item.dateType == 'daterange'
                        ? 'YYYY-MM-DD'
                        : 'YYYY-MM-DD HH:mm')
                    "
                    :date-format="item.dateFormat || 'MMM DD, YYYY'"
                    :time-format="item.timeFormat || 'HH:mm'"
                    :value-format="
                      item.valueFormat ||
                      (item.dateType == 'daterange'
                        ? 'YYYY-MM-DD'
                        : 'YYYY-MM-DD HH:mm:ss')
                    "
                    :shortcuts="item.shortcuts || []"
                    @keydown="handleKeyDown"
                    @change="
                      item.change
                        ? handleChange(item.prop)
                        : item.handleChange
                        ? item.handleChange(item.prop)
                        : ''
                    "
                    :default-time="item.defaultTime || defaultTime"
                  />
                  <!-- label_checkbox -->
                  <el-checkbox
                    v-if="item.type == 'label_checkbox'"
                    v-model="searchFormData[item.prop]"
                    :true-label="item.trueLabel"
                    :false-label="item.falseLabel"
                    :disabled="item.disabled"
                    @change="item.handleChange ? item.handleChange() : ''"
                  >
                    <span v-if="item.text">{{ $t(item.text) }}</span>
                  </el-checkbox>
                  <template
                    v-if="
                      item.type === 'label_dropdown_date_picker' ||
                      item.type === 'label_dropdown_input' ||
                      item.type === 'label_dropdown_input_clearable'
                    "
                  >
                    <div style="display: flex">
                      <el-dropdown
                        trigger="click"
                        @command="
                          item.handleCommand
                            ? item.handleCommand($event, item)
                            : ''
                        "
                      >
                        <span class="el-dropdown-link">
                          {{
                            dropFormatterLabel(item.selectValue, item.options)
                          }}
                          <el-icon class="el-icon--right">
                            <arrow-down />
                          </el-icon>
                        </span>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item
                              v-for="o in item.options || []"
                              :key="o[item.labelVal] || o.value"
                              :command="o[item.labelVal] || o.value"
                            >
                              {{ $t(o[item.labelName] || o.label) }}
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                    <el-date-picker
                      v-if="item.type === 'label_dropdown_date_picker'"
                      v-model="searchFormData[item.prop]"
                      :type="item.dateType || 'datetimerange'"
                      :disabled="item.disabled"
                      range-separator="-"
                      :start-placeholder="
                        $t(item.startPlaceholder || '开始日期')
                      "
                      :end-placeholder="$t(item.endPlaceholder || '结束日期')"
                      :picker-options="item.pickerOptions"
                      :unlink-panels="item.unlinkPanels || true"
                      :value-format="
                        item.format ? item.format : 'yyyy-MM-dd HH:mm'
                      "
                      :clearable="item.clearable ? item.clearable : false"
                      popper-class="condition-picker"
                      @keydown="handleKeyDown"
                      :default-time="[
                        new Date('2022-04-01 00:00:00'),
                        new Date('2022-04-01 23:59:59'),
                      ]"
                    />
                    <!-- label_dropdown_input_clearable 用于公共组件输入框-->
                    <!-- <input-clearable
                      v-if="item.type === 'label_dropdown_input_clearable'"
                      v-model="searchFormData[item.prop]"
                      :disabled="item.disabled"
                      @clear="item.onClear ? item.onClear() : ''"
                      @click="item.onClick ? item.onClick() : ''"
                    /> -->
                    <!-- label_dropdown_input 复合型input-->

                    <el-input
                      v-if="item.type === 'label_dropdown_input'"
                      v-model="searchFormData[item.prop]"
                      :type="item.inputType"
                      :disabled="item.disabled"
                      @keydown.ctrl.enter="handleSearch"
                      :rows="
                        item.isCollapse ? item.rows || 4 : item.collapseRows
                      "
                      :placeholder="item.placeholder || $t('请输入')"
                      clearable
                    >
                      <!-- <template v-if="item.slotType" #item.slotType>
                    {{ item.slotText }}
                  </template> -->
                      <el-select
                        v-if="item.options"
                        v-model="item.selectd"
                        @keydown.ctrl.enter="handleSearch"
                        :placeholder="item.placeholder || $t('请选择')"
                        :style="`width: ${item.width ? item.width : '100px'}`"
                        @change="
                          item.handleChange
                            ? item.handleChange(item.selectd)
                            : ''
                        "
                      >
                        <el-option
                          v-for="o in item.options || []"
                          :key="
                            o[item.labelVal] ||
                            o.value ||
                            o.subCode ||
                            o.dictCode
                          "
                          :value="
                            o[item.labelVal] ||
                            o.value ||
                            o.subCode ||
                            o.dictCode
                          "
                          :label="
                            $t(
                              o[item.labelName] ||
                                o.label ||
                                o.subName ||
                                o.dictName
                            )
                          "
                        />
                      </el-select>
                    </el-input>
                  </template>
                  <template v-if="item.type === 'slot'">
                    <slot :name="`form-${item.prop}`"></slot>
                  </template>
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </div>
        <div class="form-filter">
          <div class="form-filter-left">
            <div style="margin-top: 0" class="form-btn">
              <el-form-item label="">
                <div>
                  <div class="btn-group" v-if="queryButton">
                    <el-button
                      class="search-btn save-btn"
                      @click="handleSearch"
                      :loading="searchBtnLoading"
                      >{{ $t("查询") }}</el-button
                    >
                    <el-button class="search-btn" @click="handleReset">{{
                      $t("重置")
                    }}</el-button>
                  </div>
                  <template v-else>
                    <slot name="query-button"></slot>
                  </template>
                </div>
              </el-form-item>
            </div>
          </div>
        </div>
      </div>
    </el-form>
    <div v-if="module" class="underline"></div>
  </div>
</template>

<script setup>
import { ref, watch, computed, defineEmits, onMounted } from "vue";
import MultipleAreaInput from "./components/MultipleAreaInput.vue";
import { queryFormColumnFilters } from "@/utils/mUtils.js";
import i18n from "@/lang/index.js";
import * as api from "@/api/index.js";
const props = defineProps({
  labelPosition: {
    type: String,
    default: "right",
    valid: (val) => ["left", "right", "top"].includes(val),
  },
  gSearch: Object,
  pageVo: {
    type: Object,
    default: () => ({}),
  },

  //类型
  searchColumn: {
    type: Array,
    default: () => [],
  },
  //模块名称：
  module: {
    type: String,
    default: "",
  },
  // 必填校验
  searchRules: {
    type: Object,
    default: () => ({}),
  },
  // 数据
  searchForm: {
    type: Object,
    default: () => ({}),
  },
  // 过滤重置向
  filterParameters: {
    type: Array,
    default: () => [],
  },
  //自定义按钮
  queryButton: {
    type: Boolean,
    default: () => true,
  },
  // 查询按钮加载
  searchBtnLoading: {
    type: Boolean,
    default: false,
  },
  // 客服订单箱量统计的搜索传入表示不调两次接口
  remoteType: {
    type: Boolean,
    default: false,
  },
  // 查询表单默认查询长度
  defaultConditionLen: {
    type: Number,
    default: 4,
  },
  // 传入的样式
  defaultStyle: {
    type: Object,
    default: () => ({}),
  },
  formLoading: {
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(["handleSearch", "update:searchForm"]);
const searchColumnList = ref([]);
watch(
  () => props.searchColumn,

  (newVal) => {
    try {
      if (newVal) {
        searchColumnList.value = newVal;
      }
    } catch (error) {
      console.log(error, "error++++++=");
    }
  },
  { immediate: true, deep: true }
);
let searchFormData = computed({
  get: () => props.searchForm,
  set: (val) => {
    emits("update:searchForm", val);
  },
});
const handleSearch = () => {
  emits("handleSearch");
};
const handleReset = () => {
  for (const key in searchFormData.value) {
    if (!props.filterParameters.includes(key)) {
      delete searchFormData.value[key];
    }
  }
  emits("handleReset");
};
const onCascaderChange = (value, item) => {
  const argeObj = getAreaInfoByCodesEnhanced(item.options, value);
  item.onCascaderChange && item.onCascaderChange(argeObj);
};
function getAreaInfoByCodesEnhanced(treeData, codeList) {
  if (
    !Array.isArray(treeData) ||
    !Array.isArray(codeList) ||
    codeList.length === 0
  ) {
    return {
      provinceName: "",
      provinceCode: codeList[0] || "",
      cityName: "",
      cityCode: codeList[1] || "",
      areaName: "",
      areaCode: codeList[2] || "",
    };
  }

  const result = {
    provinceName: "",
    provinceCode: codeList[0] || "",
    cityName: "",
    cityCode: codeList[1] || "",
    areaName: "",
    areaCode: codeList[2] || "",
  };

  // 递归查找函数
  const findNode = (nodes, targetCode, level) => {
    if (!nodes || !Array.isArray(nodes)) return null;
    for (const node of nodes) {
      if (node.areaCode === targetCode) {
        // 设置对应级别的名称
        if (level === 0) result.provinceName = node.areaName;
        if (level === 1) result.cityName = node.areaName;
        if (level === 2) result.areaName = node.areaName;

        return node;
      }
    }
    return null;
  };

  let currentNodes = treeData;

  // 逐级查找
  for (let i = 0; i < codeList.length; i++) {
    const code = codeList[i];
    const node = findNode(currentNodes, code, i);

    if (!node) break; // 如果某一级没找到，停止查找

    currentNodes = node.children; // 继续在子节点中查找下一级
  }

  return result;
}

const onPropSelectClose = (item) => {
  searchFormData.value["countryCode"] = null;
  searchFormData.value["countryName"] = null;
  searchFormData.value["countryAdd"] = null;
  onCascaderClose(item);
};
const onCascaderClose = (item) => {
  searchFormData.value["provinceName"] = null;
  searchFormData.value["provinceCode"] = null;
  searchFormData.value["cityName"] = null;
  searchFormData.value["cityCode"] = null;
  searchFormData.value["areaName"] = null;
  searchFormData.value["areaCode"] = null;
  searchFormData.value[item.prop] = [];
};
onMounted(() => {
  getCountryList();
});
watch(
  () => searchFormData.value.countryCode,
  (value) => {
    if (value) {
      treeList(value);
    }
  }
);
const getCountryList = async () => {
  const c = queryFormColumnFilters(searchColumnList.value, "provinceCityArea");
  if (!c?.prop) return;
  const { rows } = await api.default.system.provinceCityArea.countryList({
    pageSize: 300,
    enableFlag: "1",
  });
  const treeData = rows.map((item) => ({
    ...item,
    label: i18n.global.t(item.countryName),
  }));
  c.propSelectOptions = treeData;
};
const onPropSelectChange = (value, item) => {
  if (item.propSelectName && value) {
    searchFormData.value[item.propSelectName] = item.propSelectOptions.find(
      (data) => data[item.propsSelect.value] === value
    )[item.propsSelect.label];
  }
  if (item.propSelectAdd && value) {
    searchFormData.value[item.propSelectAdd] = item.propSelectOptions.find(
      (data) => data[item.propsSelect.value] === value
    )[item.propsSelect.keyAdd];
  }
  if (item.onPropSelectChange && value) {
    item.onPropSelectChange(value, item);
  }
};
const treeList = async (val) => {
  const { data } = await api.default.system.provinceCityArea.treeList({
    countryCode: val,
  });
  queryFormColumnFilters(searchColumnList.value, "provinceCityArea").options =
    data;
};
const querySearchAsync = (queryString, cb, c) => {
  if(!queryString) return cb([])
  const params = {};
  params[c.paramsKey] = queryString;
  c.apiModule({
    ...params,
  }).then((res) => {
    const data = res.data || res.rows || [];
    const arr = data.map((item) => {
      const obj = {
        ...item,
      };
      obj["value"] = obj[c.value];
      return {
        ...obj,
      };
    });
    cb(arr);
  }).catch((err) => {
    cb([]);
  })
};
const handleAutocompleteSelect = (val, c) => {
  console.log(val,c);
}
const handleAutocompleteClear = (val, c) => {

}
</script>

<style scoped lang="scss">
@import "./style";
</style>
